package com.imooc.interceptor;

import com.imooc.exception.GraceException;
import com.imooc.grance.result.ResponseStatusEnum;
import com.imooc.utils.RedisOperator;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/15/16:00
 * @Description:
 */
public class BaseInterceptor {
    @Autowired
    public RedisOperator redis;

    public static final String REDIS_USER_TOKEN = "redis_user_token";
    public static final String REDIS_USER_INFO = "redis_user_info";
    public static final String REDIS_ADMIN_TOKEN = "redis_admin_token";
    public static final String ADMIN_COOKIE_TOKEN = "atoken";
    public static final String ADMIN_COOKIE_ID = "aid";
    public static final String REDIS_ALREADY_READ = "redis_already_read";


    public static final String REDIS_ADMIN_INFO = "redis_user_info";

    public boolean verifyUserIdToken(String id,String token,String redisKeyPrefix) {
        if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(token)) {
            String tokenredis = redis.get(redisKeyPrefix + ":" + id);
            System.out.println("tokenredis: "+tokenredis);
            if (!token.equalsIgnoreCase(tokenredis)) {
                GraceException.display(ResponseStatusEnum.TICKET_INVALID);
                return false;
            }
        }else {
            GraceException.display(ResponseStatusEnum.UN_LOGIN);
            return false;
        }
        return true;
    }

    public String getCookie(String key, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
